import {Directive, forwardRef, Input} from '@angular/core';
import {NG_VALIDATORS, Validator, AbstractControl, Validators} from "@angular/forms";
import {ValidatorRegexPattern} from "./validator-regex-pattern";

@Directive({
  selector: '[phoneNumber][ngModel]',
  providers: [
    {provide: NG_VALIDATORS, useExisting: forwardRef(() => PhoneNumberValidator), multi: true}
  ]
})
export class PhoneNumberValidator implements Validator {
  @Input() bypassRequiredCheck: boolean = false;

  validate(c: AbstractControl): { [key: string]: any } {
    if (!this.bypassRequiredCheck) {
      if (Validators.required(c) != undefined) {
        return null;
      }
    }

    let value = c.value;
    let isValid = ValidatorRegexPattern.phoneNumber.test(value);

    return isValid ? null : {
      phoneNumber: {
        valid: false
      }
    };
  }
}
